<template>
    <n-form
        ref="formRef"
        :rules="formRule"
        :model="formData"
        size="large"
        label-width="auto"
        label-placement="left"
        require-mark-placement="right-hanging"
    >
        <n-form-item label="所属部门" path="deptId">
            <n-popover width="trigger" placement="bottom" trigger="click">
                <template #trigger>
                    <n-input :value="deptData.name || ''" readonly placeholder="请选择所属部门" />
                </template>
                <tree @select="handleSelect" />
            </n-popover>
        </n-form-item>

        <n-form-item label="登录账号" path="username">
            <n-input v-model:value="formData.username" :minlength="4" :maxlength="50" clearable placeholder="请输入登录账号" :allow-input="(value) => !value.includes(' ')" />
        </n-form-item>

        <n-form-item label="用户姓名" path="nickname">
            <n-input v-model:value="formData.nickname" :minlength="1" :maxlength="50" clearable placeholder="请输入用户姓名" :allow-input="(value) => !value.includes(' ')" />
        </n-form-item>

        <n-form-item label="手机号" path="mobile">
            <n-input v-model:value="formData.mobile" :minlength="11" :maxlength="11" clearable placeholder="请输入手机号" :allow-input="(value) => !value.includes(' ')" />
        </n-form-item>

        <n-form-item label="是否启用" path="status">
            <n-select v-model:value="formData.status" placeholder="状态" :options="StatusOption" />
        </n-form-item>

        <n-divider />

        <n-space justify="end" size="large">
            <n-button @click="cancel">取消</n-button>
            <n-button @click="confirm" type="primary">确认</n-button>
        </n-space>
    </n-form>
</template>

<script setup lang="ts">
import {Api} from '@/api/type'
import {onMounted, ref} from 'vue'
import tree from '../dept/tree.vue'
import {BaseApi} from '@/api/base-api'
import {StatusOption} from '@/type/common'
import {FormInst, FormRules, NButton, NDivider, NForm, NFormItem, NInput, NPopover, NSelect, NSpace, useMessage} from 'naive-ui'
// -------------------------------------------------
type R<T> = Api.Common.R<T>;
type Dept = Api.System.Dept;
type Data = Api.System.User;
// -------------------------------------------------
const emit = defineEmits(['confirm', 'cancel'])

const {identity, deptId} = defineProps({
    identity: {
        type: String,
        default: ''
    },
    deptId: {
        type: String,
        default: ''
    }
})

const message = useMessage()
const deptApi = new BaseApi<Dept>('dept')
const baseApi = new BaseApi<Data>('user')
const loading = ref<boolean>(false)
const deptData = ref<Partial<Dept>>({})
const formData = ref<Data>({
    identity: '',
    deptId: '',
    username: '',
    nickname: '',
    mobile: '',
    status: 1,
    loginIp: '',
    loginTime: ''
})
const formRef = ref<FormInst | null>(null)
const formRule: FormRules = {
    deptId: [
        {
            required: true,
            trigger: ['change', 'blur'],
            validator() {
                if (!formData.value?.deptId) {
                    return new Error('请选择所属部门')
                }
                return true
            }
        }
    ],
    username: [
        {
            required: true,
            message: '请填写用户账号',
            trigger: ['input', 'blur']
        },
        {
            min: 2,
            max: 50,
            message: '用户账号长度只能在2到50个字符之间',
            trigger: ['input', 'blur']
        }
    ],
    nickname: [
        {
            required: true,
            message: '请填写账号名称',
            trigger: ['input', 'blur']
        },
        {
            min: 2,
            max: 50,
            message: '账号名称长度只能在2到50个字符之间',
            trigger: ['input', 'blur']
        }
    ],
    mobile: [
        {
            required: true,
            message: '请填写手机号',
            trigger: ['input', 'blur']
        },
        {
            min: 11,
            max: 11,
            message: '手机号长度只能是11位数字',
            trigger: ['input', 'blur']
        }
    ],
    status: [
        {
            type: 'number',
            required: true,
            message: '请选择账号状态',
            trigger: ['change', 'blur']
        }
    ]
}

async function confirm() {
    if (formData.value.identity) {
        await modifyData()
    } else {
        await additionData()
    }
    emit('confirm')
}

async function cancel() {
    emit('cancel')
}

async function additionData() {
    await formRef.value?.validate()
    loading.value = true
    let result = await baseApi.additionData(formData.value)
    if (result.code == 0) {
        message.success('添加数据成功')
    } else {
        message.error('添加数据失败.' + result.message)
    }
    loading.value = false
}

async function modifyData() {
    await formRef.value?.validate()
    loading.value = true
    let result = await baseApi.modifyData(formData.value)
    if (result.code == 0) {
        message.success('修改数据成功')
    } else {
        message.error('修改数据失败.' + result.message)
    }
    loading.value = false
}

async function handleSelect(parent: {key: string | number; label: string;}) {
    console.info('parent:', parent)
    let data = await getDeptInfo(String(parent.key || '0'))
    if (data) {
        deptData.value = data
        formData.value.deptId = data.identity
        // 这里选择完部门之后在执行一遍form校验
        formRef.value?.validate()?.catch(() => ({}))
    }
    console.info('选择父级数据:', deptData.value)
}

async function getDataInfo(identity: string): Promise<Data | null> {
    loading.value = true
    let result: R<Data> = await baseApi.getDataInfo({identity: identity})
    loading.value = false
    if (result.code == 0) {
        return result.data
    } else {
        console.error(message)
        message.error(result.message)
        return null
    }
}

async function getDeptInfo(identity: string): Promise<Dept | null> {
    loading.value = true
    let result: R<Dept> = await deptApi.getDataInfo({identity: identity})
    loading.value = false
    if (result.code == 0) {
        return result.data
    } else {
        console.error(message)
        message.error(result.message)
        return null
    }
}

async function initialize() {
    if (deptId) {
        let data = await getDeptInfo(deptId)
        if (data) {
            deptData.value = data
        } else {
            deptData.value = {}
            console.error('查询部门数据失败')
            message.error('查询部门数据失败')
        }
    }
    if (identity) {
        let data = await getDataInfo(identity)
        if (data) {
            formData.value = data
        } else {
            console.error('查询数据失败')
            message.error('查询数据失败')
        }
    }
}

onMounted(() => {
    initialize()
})
</script>
